package de.tum.icuproject.persistence.couchdb.insert;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;

import android.util.Log;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import de.tum.icuproject.Subscriber;
import de.tum.icuproject.persistence.couchdb.RequestHandler;

/**
 * Handles insert requests
 * @author stefanoturchetta
 *
 */
public class InsertRequestHandler extends RequestHandler {

	public InsertRequestHandler(Subscriber subscriber) {
		super(subscriber);	
	}

	@Override
	protected String doInBackground(String... args) {
		try {
			String requestPage = DB_URL + args[0];
			String jsonData = args[1];
			return this.doPost(requestPage, jsonData);
		} catch (ArrayIndexOutOfBoundsException e) {
			Log.e("InsertRequestHandler", "Wrong #parameters!");
		} catch (ClientProtocolException e) {
			Log.e("InsertRequestHandler", e.getMessage());
		} catch (IOException e) {
			Log.e("InsertRequestHandler", e.getMessage());
		}
		return null;
	}

	@Override
	protected void onPostExecute(String result) {
		if (result != null) {
			Log.d("RESULT", result);
			boolean confirm = this.deserializeResult(result);
			Subscriber subscriber = this.getSubscriber();
			subscriber.confirmInsertion(confirm);
		}
	}

	private boolean deserializeResult(String result) {
		JsonParser parser = new JsonParser();
		JsonObject root = parser.parse(result).getAsJsonObject();
		JsonElement elemOk = root.get("ok");
		if (elemOk != null) {
			boolean ok = elemOk.getAsBoolean();
			return ok;
		}
		// TODO: handle error in a nice way
		return false;
	}

}
